//
//  NewsViewController.swift
//  MyNews
//
//  Created by DF-Mac on 16/12/2.
//  Copyright © 2016年 DF-Mac. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire
import Kingfisher
import MJRefresh
import SVProgressHUD

class NewsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,serverResponseHandler {

    //网络请求
    var networkManager = serverManager()
//    var networkManager2 = NetworkManager()
    private var showingSocialNews = false
    private var currentPage = 1
    private let newsNumber = 10
    
    //顶部刷新
    let header = MJRefreshNormalHeader()
    //底部刷新
    let footer = MJRefreshAutoNormalFooter()
    //新闻列表数组
    var newList = [NewsDataModel]()
    //展示新闻列表数组
    var appendingNewList = [NewsDataModel]()
    //新闻列表表格
    var newsTableView : UITableView!
    
    static let cellID="newsCell"
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initialViews()
        
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(NewsViewController.headerRefresh))
        newsTableView.mj_header = header
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(NewsViewController.footerRefresh))
        newsTableView.mj_footer = footer

        //开始刷新
        newsTableView.mj_header.beginRefreshing()
        
        //初始化数据
        getNewsList()
        
    
    }
    // 顶部刷新
    func headerRefresh(){
        print("下拉刷新")
        // 结束刷新
        newsTableView.mj_header.endRefreshing()
    }
    
    // 底部刷新
    func footerRefresh(){
        print("上拉刷新")
        newsTableView.mj_footer.endRefreshing()
        // 5次后模拟没有更多数据
        
        currentPage = currentPage + 1
        getNewsList()
        if currentPage > 5 {
            footer.endRefreshingWithNoMoreData()
        }
    }

    /// 初始化视图
    ///
    /// - returns: nil
    private func initialViews(){
        
        let tableRect = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        
        newsTableView=UITableView(frame: tableRect, style: UITableViewStyle.plain)
        
        view.addSubview(newsTableView)
        
        newsTableView.backgroundColor=UIColor.white
        
        newsTableView.delegate=self
        newsTableView.dataSource=self
        
        newsTableView.register(NewsListViewCell.classForCoder(), forCellReuseIdentifier: NewsViewController.cellID)
        //方法一:使用代理
        //networkManager.requestDelegate=self
        //方法二:执行方法调用
        //getNewsList()
    }
    
    /*
    //用Alamofire请求数据(默认未调用)
    private func loadData2() -> () {
        
        if showingSocialNews {
            return
        }

        showingSocialNews=true
        
        Alamofire.request(NetworkManager.newsType.socialNews(newsNumber,currentPage)).responseJSON { (dataResponse) in
            print("result\(dataResponse.result)")
            switch dataResponse.result{
            case .success(let dict):
                //print(dict)
                let json = JSON(data: dataResponse.data!)
                //print(json)
                if let newListArray = json["newslist"].array{
                    for newDict in newListArray {
                        let newData = NewsDataModel(ctime: newDict["ctime"].string, title: newDict["title"].string, picUrl: newDict["picUrl"].string, url: newDict["url"].string, description: newDict["description"].string)
                        self.appendingNewList.append(newData)
                    }
                }
                
                self.newList = self.newList+self.appendingNewList
                DispatchQueue.main.async(execute: {
                    self.newsTableView.reloadData()
                })
                
            case .failure(let error):
                print(error)
                
            }
            
        }
        
    }
    //这部分是用来测试API是否可用
    func loadData() -> Void {

        let urlC = "http://api.tianapi.com/social"
        let paramters:Parameters = ["key":"6bcc592cde9eec424cb2cb17d4c82ced"]
        Alamofire.request(urlC, method: .get, parameters: paramters)
            .responseJSON { response in
                debugPrint(response)
        }
        
    }
    
    */
    /// 请求数据
    private func getNewsList(){
        if appendingNewList.count>0 {
            appendingNewList.removeAll(keepingCapacity: false)
        }
        networkManager.getNews(newsType: "social", num: newsNumber, page: currentPage)
        
        //方法二:设置编辑完成的闭包,tag用于多个网络请求方法的标识
        networkManager.completionCallBack={
            (tag,data) in
            let json = JSON(data: data)
            
            if let newListArray = json["newslist"].array{
                for newDict in newListArray {
                    let newData = NewsDataModel(ctime: newDict["ctime"].string, title: newDict["title"].string, picUrl: newDict["picUrl"].string, url: newDict["url"].string, description:newDict["description"].string)
                    self.appendingNewList.append(newData)
                }
            }
            
            self.newList = self.newList+self.appendingNewList
            //主线程更新UI
            DispatchQueue.main.async(execute: {
                self.newsTableView.reloadData()
            })
            
        }
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK: TableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return newList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: NewsViewController.cellID, for: indexPath) as! NewsListViewCell
        
        cell.newsDataModel=newList[(indexPath as NSIndexPath).row]
        
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detaiVC = NewsDetailViewController()
        
        detaiVC.title = newList[(indexPath as NSIndexPath).row].title
        
        detaiVC.newsUrl=newList[(indexPath as NSIndexPath).row].url
        
        navigationController?.pushViewController(detaiVC, animated: true)
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    //MARK: requestDelegate
    func requestFinished(_ responseData: Data, requestTag: Int) {

        let json = JSON(data: responseData)
        
        if let newListArray = json["newslist"].array{
            for newDict in newListArray {
                let newData = NewsDataModel(ctime: newDict["ctime"].string, title: newDict["title"].string, picUrl: newDict["picUrl"].string, url: newDict["url"].string, description: newDict["description"].string)
                self.appendingNewList.append(newData)
            }
        }
        
        self.newList = self.newList+self.appendingNewList
        //主线程更新UI
        DispatchQueue.main.async(execute: {
            self.newsTableView.reloadData()
        })

    }
    func requestFailed(_ error: NSError) {
        print("news error=\(error)")
    }
    


}
